package com.briup.corejava.day22;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

/**
 * 反射的应用场景
 * 反射的时机：运行时修改
 * 向List<Integer>中添加字符串和double
 */
public class Test1 {
    public static void main(String[] args) {
        // 准备集合
        List<Integer> list = new ArrayList<>();
        // 使用反射获取add方法，进行元素添加
        Class<? extends List> clazz = list.getClass();
        try {
            Method add = clazz.getMethod("add", Object.class);
            // 调用方法
            add.invoke(list,"字符串");
            add.invoke(list,20);
            add.invoke(list,20.45);
            // 输出
            System.out.println("list = " + list);

        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }
}
